from .pre_parser import create_pre_parser
from .command_parser import create_command_parser, create_source_parser
from alteraparser.ast import AST

class SchabloneskParser(object):
    
    def __init__(self):
        self.__pre_parser = create_pre_parser()
        self.__cmd_parser = create_command_parser()
        self.__src_parser = create_source_parser()
        
    def parse_file(self, filepath):
        ast = self.__pre_parser.parse_file(filepath)
        if not ast:
            return None
        lines = self.__analyse(ast)
        res = AST('schablonesk')
        for line in lines:
            line_type, data = line
            if line_type == 'C':
                parser = self.__cmd_parser
            else:
                parser = self.__src_parser
            line_ast = parser.parse_string(data)
            if line_ast:
                res.add_child(line_ast)
            else:
                return None
        return res
        
    def __analyse(self, ast):
        prev_type = None
        prev_to_be_cont = False
        cmd = ''
        res = []
        for child in ast.get_ast_children():
            if child.name == 'command':
                cmd_part = child.get_text()
                if prev_type == 'cmd' and prev_to_be_cont:
                    cmd += ' ' + cmd_part
                else:
                    if cmd:
                        res.append(('C', cmd))
                    cmd = cmd_part
                prev_type = 'cmd'
                prev_to_be_cont = bool(child['continued'])
            else:
                if prev_type == 'cmd':
                    res.append(('C', cmd))
                    cmd = ''
                res.append(('S', child.get_text()))
                prev_type = 'src'
        if cmd:
            res.append(('C', cmd))
        return res
            